#include <iostream>
#include "helper.h"

using namespace std;
// 21.合并两个有序链表
// 将两个升序链表合并为一个新的 升序 链表并返回。新链表是通过拼接给定的两个链表的所有节点组成的。

class Solution {
public:
    ListNode* mergeTwoLists(ListNode* list1, ListNode* list2) {
        auto *dummyHead = new ListNode(INT_MIN);
        ListNode *p = dummyHead, *p1 = list1, *p2 = list2;

        while(p1 != nullptr && p2 != nullptr) {
            if(p1->val <= p2->val) {
                p->next = p1;
                p = p1;
                p1 = p1->next;
            } else if(p1->val > p2->val) {
                p->next = p2;
                p = p2;
                p2 = p2->next;
            }

            p->next = nullptr;
        }
        while (p1 != nullptr) {
            p->next = p1;
            p = p1;
            p1 = p1->next;
        }
        while (p2 != nullptr) {
            p->next = p2;
            p = p2;
            p2 = p2->next;
        }

        ListNode *retNode = dummyHead->next;

        delete dummyHead;

        return retNode;
    }
};

int main() {
    int arr1[] = {1, 2, 4};
    int n1 = sizeof(arr1)/sizeof(int);

    ListNode* head1 = createLinkedList(arr1, n1);
    printLinkedList(head1);

    int arr2[] = {1, 3, 4};
    int n2 = sizeof(arr2)/sizeof(int);

    ListNode* head2 = createLinkedList(arr2, n2);
    printLinkedList(head2);

    ListNode* head3 = Solution().mergeTwoLists(head1,head2);
    printLinkedList(head3);

    return 0;
}
